package com.example.Service;

import com.example.utils.VivoAuth;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文本相似度匹配
 */
@Service
public class RerankService {
    private static final String APP_ID = "2025985389";
    private static final String APP_KEY = "eAkRKtYXOawsmtVv";
    private static final String DOMAIN = "api-ai.vivo.com.cn";
    private static final String URI = "/rerank";
    private static final String METHOD = "POST";

    public String rerank(String query,String[] sentences) throws UnsupportedEncodingException {
        // 构造请求参数
        Map<String, Object> params = new HashMap<>();
        
        // 构造请求体
        Map<String, Object> postData = new HashMap<>();
        postData.put("model_name", "bge-reranker-large");
        //query与sentences中的每一段文字对比
        postData.put("query", query);
        postData.put("sentences", sentences);

        // 生成签名头
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, "");

        // 发送请求
        String url = "https://" + DOMAIN + URI;
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(postData, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println(response.getBody());
        } else {
            System.out.println(response.getStatusCode() + " " + response.getBody());
        }
        return response.getBody();
    }

}
